package cn.itsource.org.service.impl;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.SecureUtil;
import cn.itsource.org.domain.TbUser;
import cn.itsource.org.mapper.TbUserMapper;
import cn.itsource.org.qury.UserQuery;
import cn.itsource.org.service.TbUserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
public class TbUserServiceImpl implements TbUserService {
    @Autowired
    private TbUserMapper tbUserMapper;

    @Override
    @Transactional
    public int deleteByPrimaryKey(Long id) {
        return tbUserMapper.deleteByPrimaryKey(id);
    }


    @Override
    public int insert(TbUser record) {
        return tbUserMapper.insert(record);
    }

    @Override
    @Transactional
    public void save(TbUser user) {
        if (user.getId() == null) {
            //动态生成盐值
            String salt = RandomUtil.randomString(20);
            user.setSalt(salt);
            user.setPassword(SecureUtil.md5(user.getPassword() + user.getSalt()));
            tbUserMapper.insert(user);
        }else{
            tbUserMapper.updateByPrimaryKeySelective(user);
        }
    }

    @Override
    public int insertSelective(TbUser record) {
        return tbUserMapper.insertSelective(record);
    }

    @Override
    public TbUser selectByPrimaryKey(Long id) {
        return  tbUserMapper.selectByPrimaryKey(id);
    }

    @Override
    public int updateByPrimaryKeySelective(TbUser record) {
        return  tbUserMapper.updateByPrimaryKeySelective(record);
    }

    @Override
    public int updateByPrimaryKey(TbUser record) {
        return  tbUserMapper.updateByPrimaryKey(record);
    }

    @Override
    public PageInfo<TbUser> pageInfo(UserQuery userQuery) {
        PageHelper.startPage(userQuery.getCurrentPage(), userQuery.getPageSize());
        List<TbUser> tbUsers = tbUserMapper.quertAll(userQuery);
        return new  PageInfo<TbUser>(tbUsers);
    }

    @Override
    @Transactional
    public void BatchDelete(List<TbUser> users) {
    tbUserMapper.deleteByCollection(users);
    }

    @Override
    public Boolean exist(TbUser user) {
        TbUser userByDB = tbUserMapper.selectByUsername(user.getUserName());
        if (user.getId() == null) {
            return userByDB == null;
        }else{
            if (userByDB == null) {
                return true;
            }else{
                return userByDB.getId().equals(user.getId());
            }
        }
    }
}
